<template>
	<view class="bg-white">
		<uv-form labelPosition="left" labelWidth="120" :model="formData" :rules="rules" ref="form">
			<view class="title">
				基本信息
			</view>
			<view class="padding-lr">
				<uv-form-item label="头像" prop="avatar" borderBottom>
					<!--        <view class="flex justify-end w-100" @click="updateAvatar">-->
					<view class="flex justify-end w-100">
						<!-- <view class='cu-avatar round '></view> -->
						<!--              <ImageUpload :maxCount='1' v-model="formData.avatar">-->
						<!--                <view slot="img">-->
						<!--                  <uv-avatar :src="'http://localhost:9005/common/file/'+formData.avatar"></uv-avatar>-->
						<!--                </view>-->
						<!--              </ImageUpload>-->
						<uv-avatar v-if="formData.avatar" :src="`${imgUrl}${formData.avatar}`"
							@click="chooseImg"></uv-avatar>
						<uv-avatar v-else="formData.avatar" :src="`${$hd.baseUrl}/images/flyer.png`"
							@click="chooseImg"></uv-avatar>
					</view>
				</uv-form-item>
				<uv-form-item label="姓名" prop="name" borderBottom :required="true">
					<uv-input v-if="formData.authStatus!=1" v-model="formData.name" placeholder="请输入姓名"
						inputAlign="right" border="none">
					</uv-input>
					<uv-input v-else v-model="formData.name" disabled disabledColor="#e9ecef" placeholder="请输入姓名"
						inputAlign="right" border="none">
					</uv-input>
				</uv-form-item>
				<uv-form-item label="手机" prop="contact" borderBottom>
					<uv-input v-model="formData.contact" disabled disabledColor="#e9ecef" border="none"
						inputAlign="right">
					</uv-input>
				</uv-form-item>
				<uv-form-item label="性别" prop="sex" borderBottom @click="showSexSelect">
					<uv-input v-model="formData.sex" disabled disabledColor="#ffffff" placeholder="请选择性别"
						inputAlign="right" border="none">
					</uv-input>
					<template v-slot:right>
						<uv-icon name="arrow-right"></uv-icon>
					</template>
				</uv-form-item>
				<!-- <uv-form-item label="地址" prop="address" borderBottom>
					<uv-textarea :maxlength="-1" autoHeight v-model="formData.address" border="none"
						:textStyle="{textAlign: 'right'}" inputAlign="right" placeholder="请输入地址">
					</uv-textarea>
				</uv-form-item> -->
				<uv-form-item v-if="theme=='fs'" label="期望接单区域" prop="desiredServiceAreaName" borderBottom
					@click="showPicker()">
					<uv-input v-model="formData.desiredServiceAreaName" disabled disabledColor="#ffffff" inputAlign="right"
						placeholder="请选择期望接单区域" border="none">
					</uv-input>
					<template v-slot:right>
						<uv-icon name="arrow-right"></uv-icon>
					</template>
				</uv-form-item>
				<uv-button :color="theme == 'fs'? '#006BFE' : '#0CCA89'" size="normal" text="提交" customStyle="margin-top: 10px"
					@click="submit"></uv-button>
			</view>

			<!--      <view class="title margin-top">-->
			<!--        收款信息-->
			<!--      </view>-->
			<!--      <view class="padding-lr">-->
			<!--        <uv-form-item label="收款姓名" prop="paymentName" borderBottom>-->
			<!--          <uv-input v-model="formData.paymentName" placeholder="请输入收款姓名" inputAlign="right" border="none">-->
			<!--          </uv-input>-->
			<!--        </uv-form-item>-->
			<!--        <uv-form-item label="收款账号" prop="paymentNumber" borderBottom>-->
			<!--          <uv-input v-model="formData.paymentNumber" placeholder="请输入收款账号" inputAlign="right" border="none">-->
			<!--          </uv-input>-->
			<!--        </uv-form-item>-->
			<!--        <uv-form-item label="开户行" prop="openBank" borderBottom>-->
			<!--          <uv-input v-model="formData.openBank" placeholder="请输入开户行" inputAlign="right" border="none">-->
			<!--          </uv-input>-->
			<!--        </uv-form-item>-->
			<!--        <uv-form-item label="银行类型" prop="bankType" borderBottom @click="showPickerBank()">-->
			<!--          <uv-input v-model="formData.bankType" disabled disabledColor="#ffffff" inputAlign="right"-->
			<!--                    placeholder="请选择银行类型" border="none">-->
			<!--          </uv-input>-->
			<!--          <template v-slot:right>-->
			<!--            <uv-icon name="arrow-right"></uv-icon>-->
			<!--          </template>-->
			<!--        </uv-form-item>-->

			<!--        -->
			<!--        &lt;!&ndash; <uv-button type="error" text="重置" customStyle="margin-top: 10px" @click="reset"></uv-button> &ndash;&gt;-->





			<!--        &lt;!&ndash; <uv-action-sheet ref="typeSelect" :actions="actions" title="请选择异常类型" @select="typeConfirm">-->
			<!--        </uv-action-sheet> &ndash;&gt;-->

			<!--        &lt;!&ndash; <view class="foot-box">-->
			<!--          <button class="cu-btn bg-main flex-sub">提交</button>-->
			<!--        </view> &ndash;&gt;-->
			<!--      </view>-->

		</uv-form>

		<uv-action-sheet ref="sexSelect" :actions="actionsSex" title="请选择性别" @select="sexSelect">
		</uv-action-sheet>

		<!--期望地址-->
		<!-- <uv-picker ref="picker1" :columns="actions" @confirm="confirm"></uv-picker> -->
		<uv-action-sheet ref="picker1" :actions="actions" title="请选择期望地址" @select="confirm">
		</uv-action-sheet>
		<!--银行类型-->
		<uv-picker ref="picker2" :columns="actionsBank" @confirm="confirmBank"></uv-picker>

	</view>
</template>
<script>
	import {
		selectDictLabel
	} from '@/utils/huida.js'
	import {
		mapGetters
	} from 'vuex'
	export default {
		computed: {
			...mapGetters(['theme'])
		},
		data() {
			return {
				timer: null,
				imgUrl: this.$hd.baseUrl + '/common/file/',
				formData: {
					id: '',
					uid: '',
					name: '',
					contact: '',
					sex: '',
					gender: '',
					desiredServiceArea: '',
					desiredServiceAreaName: '',
					address: '',
					avatar: '',
					paymentName: '',
					paymentNumber: '',
					bankType: '',
					authStatus: '', //认证状态，1已认证
					openBank: ''
				},
				fileList: [],
				dateValue: Number(new Date()),
				actionsSex: [{
					name: '男',
				}, {
					name: '女',
				}, {
					name: '未知',
				}],
				actions: [
					// ['南宁市兴宁区', '南宁市江南区', '南宁市青秀区', '南宁市西乡塘区', '南宁市邕宁区', '南宁市良庆区', '南宁市武鸣区']
				],
				actionsBank: [
					['工商银行', '中国银行', '建设银行', '农业银行']
				],
				rules: {
					'name': {
						type: 'string',
						required: true,
						message: '请输入名字',
						trigger: ['blur', 'change']
					},
					'contact': {
						type: 'string',
						required: true,
						message: '请输入联系方式',
						trigger: ['blur', 'change']
					},
					'sex': {
						type: 'string',
						required: true,
						message: '请选择性别',
						trigger: ['blur', 'change']
					},
					'address': {
						type: 'string',
						required: true,
						message: '请输入地址',
						trigger: ['blur', 'change']
					},
					'desiredServiceAreaName': {
						type: 'string',
						required: true,
						message: '请选择期望区域',
						trigger: ['blur', 'change']
					},
					'paymentName': {
						type: 'string',
						required: true,
						message: '请输入收款人姓名',
						trigger: ['blur', 'change']
					},
					'paymentNumber': [
						// {
						//   type: 'number',
						//   required: true,
						//   len: 11,
						//   message: '请填写正确的银行账号',
						//   trigger: ['blur']
						// },
						{
							type: 'number',
							required: true,
							message: '请输入收款人账号',
							trigger: ['blur', 'change']
						}
					],
					'bankType': [{
						type: 'string',
						required: true,
						message: '请选择银行类型',
						trigger: ['change']
					}],
					'openBank': {
						type: 'string',
						required: true,
						message: '请输入开户行',
						trigger: ['blur', 'change']
					},
				},
				radio: '',
				switchVal: false
			}

		},
		onUnload() {
			this.clearInterval()
		},
		onLoad() {
			uni.$uv.http.get('/system/dict/data/type/expected_range').then(res => {
				this.actions = res.data.map(item => ({
					name: item.dictLabel,
					label: item.dictLabel,
					value: item.dictValue
				}))
				this.getInfo();
			})
			if (this.theme == 'farmer') {
				uni.setNavigationBarColor({
					backgroundColor: '#0BCA89',
					frontColor: '#ffffff',
					success(res) {
						console.log('success', res)
					},
					fail(err) {
						console.log('err123', err)
					}
				});
			} else {
				uni.setNavigationBarColor({
					backgroundColor: '#006BFE',
					frontColor: '#ffffff',
				});
			}
		},
		mounted() {
			//获取裁切页面返回的图片
			uni.$on('uAvatarCropper', (data) => {
				this.uAvatarCropper(data)
			});
		},
		methods: {
			chooseImg() {
				const _this = this;
				uni.chooseImage({
					count: 1,
					sizeType: ['original', 'compressed'],
					sourceType: ['album'],
					success: function(res) {
						_this.uploadFilePromise(res.tempFilePaths[0]).then(function(data) {
							_this.formData.avatar = data.data.id
						})
					}
				});
			},

			getInfo() {
				this.$http.get(`/cadre/${this.theme == 'fs'? 'flyerManage': 'farmerManage'}/getFlyerInfo`).then(res => {
					this.formData.id = res.data.id
					this.formData.uid = res.data.user.id
					this.formData.name = res.data.name
					this.formData.contact = res.data.contact
					this.formData.authStatus = res.data.authStatus
					if (res.data.user.gender == 0) {
						this.formData.sex = '男'
					} else if (res.data.user.gender == 1) {
						this.formData.sex = '女'
					} else this.formData.sex = '未知'
					this.formData.desiredServiceArea = res.data.desiredServiceArea
					this.formData.desiredServiceAreaName = selectDictLabel(this.actions, res.data.desiredServiceArea)
					this.formData.address = res.data.address
					this.formData.avatar = res.data.user.avatar
					this.formData.paymentName = res.data.paymentName
					this.formData.paymentNumber = res.data.paymentNumber
					this.formData.bankType = res.data.bankType
					this.formData.openBank = res.data.openBank
				})
			},

			//打开区域选择
			showPicker() {
				this.$refs.picker1.open();
			},
			//打开银行类型选择
			showPickerBank() {
				this.$refs.picker2.open();
			},
			//区域选择
			confirm(e) {
				console.log('e', e)
				this.formData.desiredServiceArea = e.value
				this.formData.desiredServiceAreaName = e.name
				// this.formData.desiredServiceArea = e.value[0]
			},
			//银行类型选择
			confirmBank(e) {
				this.formData.bankType = e.value[0]
			},

			// 提交
			submit() {
				var _this = this;
				// 如果有错误，会在catch中返回报错信息数组，校验通过则在then中返回true
				this.$refs.form.validate().then(res => {

					if (_this.formData.sex == '男') {
						_this.formData.gender = 0
					} else if (_this.formData.sex == '女') {
						_this.formData.gender = 1
					} else _this.formData.gender = 2
					let params = {
						id: _this.formData.id,
						name: _this.formData.name,
						contact: _this.formData.contact,
						userId: _this.formData.uid,
						user: {
							id: _this.formData.uid,
							gender: _this.formData.gender,
							avatar: _this.formData.avatar
						},
						desiredServiceArea: _this.formData.desiredServiceArea,
						address: _this.formData.address,
						paymentName: _this.formData.paymentName,
						paymentNumber: _this.formData.paymentNumber,
						bankType: _this.formData.bankType,
						openBank: _this.formData.openBank
					}
					if (_this.formData.id == null) {
						_this.$http.post(`/cadre/${this.theme == 'fs'? 'flyerManage': 'farmerManage'}/add`, {}, {
							data: params
						}).then(res => {
							if (res.code == 200) {
								uni.showToast({
									icon: 'success',
									title: res.msg
								})
								_this.timer = setInterval(() => {
									uni.reLaunch({
										url: '/pages/mine/index'
									})
								}, 1000)
							} else {
								uni.showToast({
									icon: 'error',
									title: res.msg
								})
							}
						})
					} else {
						_this.$http.put(`/cadre/${this.theme == 'fs'? 'flyerManage': 'farmerManage'}/editFlyerInfo`, {}, {
							data: params
						}).then(res => {
							if (res.code == 200) {
								uni.showToast({
									icon: 'success',
									title: res.msg
								})
								_this.timer = setInterval(() => {
									uni.reLaunch({
										url: '/pages/mine/index'
									})
								}, 1000)
							} else {
								uni.showToast({
									icon: 'error',
									title: res.msg
								})
							}
						})
					}
				}).catch(errors => {
					uni.showToast({
						icon: 'error',
						title: '信息未完善'
					})
				})
			},
			// 重置
			reset() {
				this.$refs.form.resetFields();
				this.$refs.form.clearValidate();
			},
			openTime() {
				this.$refs.datetimePicker.open();
			},
			// 类型选择
			showTypeSelect() {
				// this.$refs.typeSelect.open();
				this.hideKeyboard();
			},
			// 类型选择返回结果
			typeConfirm(e) {
				this.formData.desiredServiceArea = e.name
				// this.model1.userInfo.sex = e.name;
				// 对部分表单字段进行校验
				// this.$refs.form.validateField('userInfo.sex', err => {
				// 	// 处理错误后的逻辑
				// })
			},
			// 性别选择
			showSexSelect() {
				this.$refs.sexSelect.open();
				this.hideKeyboard();
			},
			// 性别选择返回结果
			sexSelect(e) {
				this.formData.sex = e.name;
				// 对部分表单字段进行校验
				// this.$refs.form.validateField('userInfo.sex', err => {
				// 	// 处理错误后的逻辑
				// })
			},
			hideKeyboard() {
				uni.hideKeyboard()
			},
			updateAvatar() {
				uni.$uv.route('/pages/common/AvatarCropper', {
					destWidth: '500',
					rectWidth: '300',
					fileType: 'png',
				});
			},
			//裁剪返回方法
			async uAvatarCropper(data) {
				let url = null;
				await base64ToPath(data).then(res => {
					url = res;
				})
				uni.uploadFile({
					url: this.$hd.baseUrl + '/common/upload', // 仅为示例，非真实的接口地址
					filePath: url,
					name: 'file',
					formData: {
						// user: 'test'
					},
					header: {
						Authorization: "Bearer " + uni.getStorageSync('token'),
					},
					success: (res) => {

					}
				});

			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: this.$hd.baseUrl + '/common/upload',
						filePath: url,
						name: 'file',
						formData: {
							// user: 'test'
						},
						header: {
							Authorization: "Bearer " + uni.getStorageSync('token'),
						},
						success: (res) => {
							resolve(JSON.parse(res.data))
						}
					});
				})
			},
			clearInterval() {
				if (this.timer) {
					clearInterval(this.timer)
					this.timer = null
				}
			},

		}
	}
</script>

<style lang="scss" scoped>
	.title {
		background-color: #F3F4F5;
		width: 100%;
		height: 100rpx;
		line-height: 100rpx;
		font-size: 32rpx;
		font-weight: bold;
		padding-left: 20rpx;
	}

	.foot-box {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 20rpx;
		background-color: #fff;
	}
</style>